import React, { Component } from 'react'
import styles from './index.module.scss'
import { getAllChannels } from 'api/channel'
import { getAllArticles } from 'api/article'
import {
  Breadcrumb,
  Divider,
  Form,
  Radio,
  Button,
  DatePicker,
  Alert,
  Table,
  Image,
  Tag,
  Space,
  message,
} from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { status, defaultImg } from 'api/constant'
import { removeArticle } from 'api/article'
import SelectChannel from 'components/SelectChannel'
const { RangePicker } = DatePicker

export default class Article extends Component {
  state = {
    articles: [],
    total: 0,
    pages: {
      page: 1,
      per_page: 1,
    },
    filterParams: null,
    columns: [
      {
        title: '封面',
        render(data) {
          return (
            <Image
              width={200}
              height={150}
              src={data.cover.images[0] || 'error'}
              fallback={defaultImg}
            />
          )
        },
      },
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render(value) {
          return <Tag color={status[value].color}>{status[value].text}</Tag>
        },
      },
      {
        title: '发布时间',
        dataIndex: 'pubdate',
        key: 'pubdate',
      },
      {
        title: '阅读数',
        dataIndex: 'read_count',
        key: 'read_count',
      },
      {
        title: '评论数',
        dataIndex: 'comment_count',
        key: 'comment_count',
      },
      {
        title: '点赞数',
        dataIndex: 'like_count',
        key: 'like_count',
      },
      {
        title: '操作',
        render: (data) => {
          return (
            <Space>
              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined />}
                onClick={() =>
                  this.props.history.push('/home/publish/' + data.id)
                }
              ></Button>
              <Button
                type="primary"
                shape="circle"
                danger
                icon={<DeleteOutlined />}
                onClick={() => this.deleteArticle(data.id)}
              ></Button>
            </Space>
          )
        },
      },
    ],
  }

  deleteArticle = async (id) => {
    const { articles, pages } = this.state
    try {
      await removeArticle(id)
      message.success('删除成功')
      this.setState(
        {
          articles: articles.filter((item) => item.id !== id),
          pages: {
            ...pages,
            page:
              articles.length === 1 && pages.page !== 1
                ? pages.page - 1
                : pages.page,
          },
        },
        () => {
          this.pageOnChange()
        }
      )
    } catch (err) {
      message.error('删除失败')
    }
  }

  onFinish = async (values) => {
    const params = {}
    params.status = values.status === -1 ? null : values.status
    if (values.time) {
      params.begin_pubdate = values.time[0].format('YYYY-MM-DD')
      params.end_pubdate = values.time[1].format('YYYY-MM-DD')
    }
    params.channel_id = values.channel
    const res = await getAllArticles({ ...params, ...this.state.pages })
    this.setState({
      articles: res.data.results,
      total: res.data.total_count,
      filterParams: params,
    })
  }

  pageOnChange = async (page) => {
    const { pages, filterParams } = this.state
    const res = await getAllArticles({
      page,
      per_page: pages.per_page,
      ...filterParams,
    })
    this.setState({
      pages: { ...pages, page },
      articles: res.data.results,
      total: res.data.total_count,
    })
  }

  render() {
    const { channels, articles, total, pages, columns } = this.state
    return (
      <div className={styles.article}>
        <Breadcrumb>
          <Breadcrumb.Item
            onClick={() => {
              this.props.history.push('/home')
            }}
          >
            首页
          </Breadcrumb.Item>
          <Breadcrumb.Item>内容管理</Breadcrumb.Item>
        </Breadcrumb>
        <Divider />
        {/* 表单 */}
        <Form
          name="basic"
          initialValues={{
            status: -1,
            channel: 0,
          }}
          onFinish={this.onFinish}
        >
          <Form.Item name="status" label="状态">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="channel" label="频道:" wrapperCol={{ span: 3 }}>
            <SelectChannel />
          </Form.Item>
          <Form.Item name="time" label="日期">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>

        {total ? (
          <Alert
            message={`根据筛选条件共查询到 ${total} 条结果：`}
            type="info"
          />
        ) : null}

        <Table
          rowKey="id"
          dataSource={articles}
          columns={columns}
          pagination={{
            position: ['bottomCenter'],
            current: pages.page,
            pageSize: pages.per_page,
            total,
            onChange: this.pageOnChange,
          }}
        />
      </div>
    )
  }
}
